﻿using CCWin.SkinControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NikeSale.Models;
using static NikeSale.Bll.DBSelect;
using NikeSale.Bll;

namespace NikeSale.Ull
{
    public partial class CashierForm : Form
    {
        LoginInfo User;

        public CashierForm(LoginInfo info)
        {
            this.User = info;
            InitializeComponent();
            Initialize();
            this.lb_Cashier.Text = "收银员:" + User.UserName;
            this.WindowState = FormWindowState.Maximized;
        }

        //初始化部分事件
        private void Initialize()
        {
            this.tb_Actual.SkinTxt.KeyPress += SkinTxt_DecimalCheck_KeyPress;
            this.tb_ArticleNo.SkinTxt.KeyPress += SkinTxt_NumberCheck_KeyPress;

            this.cb_Guid.Items.AddRange(DBSelect.Guides);
            this.cb_Guid.SelectedIndex = 0;
        }

        private void lv_AVGColumn_SizeChanged(object sender, EventArgs e)
        {
            SkinListView view = sender as SkinListView;
            view.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.HeaderSize);
            int avgWidth = (view.Width - view.Columns[0].Width) / view.Columns.Count - 1;
            for (int i = 1; i < view.Columns.Count; i++)
            {
                view.Columns[i].Width = avgWidth;
            }
        }

        private void SkinTxt_NumberCheck_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == (int)Keys.Back) return;
            if (char.IsNumber(e.KeyChar)) return;
            e.Handled = true;
        }

        private void SkinTxt_DecimalCheck_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == (int)Keys.Decimal) return;
            if ((int)e.KeyChar == (int)Keys.Delete) return;
            if ((int)e.KeyChar == (int)Keys.Back) return;
            if (char.IsNumber(e.KeyChar)) return;
            e.Handled = true;
        }

        private void bt_Confirm_Click(object sender, EventArgs e)
        {
            if (this.tb_ArticleNo.Text.Length != 6)
            {
                Methods.ShowPrompt("货号格式不合法");
                return;
            }
            int ind = SalesIDSesting(this.tb_ArticleNo.Text);
            if (ind < 0)
            {
                Goods gds = Cashier.GetGoods(this.tb_ArticleNo.Text);
                if (gds == null)
                {
                    Methods.ShowPrompt(" 货号不存在", 1000);
                    return;
                }
                string[] rows = new string[]
                {
                gds.GoodsID,
                gds.BarCode,
                gds.GoodsName,
                gds.GoodsTypeName,
                gds.StorePrice,
                gds.SalePrice,
                gds.Discount,
                Math.Round((double.Parse(gds.SalePrice)*double.Parse(gds.Discount)),2).ToString("#0.00"),
                "1"
                };
                this.dgv_SettlementList.Rows.Add(rows);
            }
            else
            {
                int count = int.Parse(this.dgv_SettlementList.Rows[ind].Cells["cm_Num"].Value.ToString());
                this.dgv_SettlementList.Rows[ind].Cells["cm_Num"].Value = ++count;
            }
            this.Statistics();
        }

        private void bt_Settlement_Click(object sender, EventArgs e)
        {
            if (this.dgv_SettlementList.Rows.Count == 0)
            {
                Methods.ShowPrompt("没有商品可以结算");
                return;
            }
            if (this.tb_Actual.Text.Length == 0)
            {
                Methods.ShowPrompt("实收项不能为空");
                return;
            }
            if (double.Parse(this.tb_Actual.Text) < double.Parse(this.tb_Receivable.Text))
            {
                Methods.ShowPrompt("实收项不能小于应收项");
                return;
            }
            this.CalculatedExpenditure();
            this.dgv_SettlementList.Rows.Clear();
        }

        private void bt_Clear_Click(object sender, EventArgs e)
        {
            this.DataClear();
        }

        //动态设置enter热键
        private void tb_ArticleNo_Enter(object sender, EventArgs e)
        {
            this.AcceptButton = this.bt_Confirm;
        }
        private void tb_Actual_Enter(object sender, EventArgs e)
        {
            this.AcceptButton = this.bt_Settlement;
        }

        //单击每行的删除按钮时删除整行
        private void dgv_SettlementList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != this.dgv_SettlementList.ColumnCount - 1)
            {
                return;
            }
            this.dgv_SettlementList.Rows.RemoveAt(e.RowIndex);
            
        }

        //删除行时重新计算应收价格
        private void dgv_SettlementList_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (this.dgv_SettlementList.Rows.Count == 0)
            {
                this.tb_Receivable.Text = "0.00";
                return;
            }
            this.Statistics();
        }

        //数量文本输入时触发事件,以及设置他们的最大最小值
        private void dgv_SettlementList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgv_SettlementList.Columns[e.ColumnIndex].Name.Equals("cm_Num"))
            {
                if (Convert.ToInt32(this.dgv_SettlementList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) < 1)
                {
                    this.dgv_SettlementList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1;
                }
                if (Convert.ToInt32(this.dgv_SettlementList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) > 10)
                {
                    this.dgv_SettlementList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 10;
                }
                if (!Cashier.GoodsQuantityCompare(
                   this.dgv_SettlementList.Rows[e.RowIndex].Cells["cm_GoodsID"].Value.ToString(),
                   int.Parse(this.dgv_SettlementList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())))
                {
                    MessageBox.Show("商品" + this.dgv_SettlementList.Rows[e.RowIndex].Cells["cm_GoodsName"].Value.ToString() + "的库存不够了!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    this.dgv_SettlementList.Rows.RemoveAt(e.RowIndex);
                    return;
                }
            }
            Statistics();
        }

        //约束数量输入格式
        private void dgv_SettlementList_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dgv_SettlementList.CurrentCell.ColumnIndex == this.dgv_SettlementList.ColumnCount - 2)
            {
                e.Control.KeyPress -= SkinTxt_NumberCheck_KeyPress;
                e.Control.KeyPress += SkinTxt_NumberCheck_KeyPress;
            }
        }

        #region 方法
        /// <summary>
        /// 返回列表中包含指定货号的行索引,如果没找到则返回-1;
        /// </summary>
        private int SalesIDSesting(string id)
        {
            for (int i = 0; i < this.dgv_SettlementList.Rows.Count; i++)
            {
                if (this.dgv_SettlementList.Rows[i].Cells["cm_ArticleNo"].Value.ToString().Equals(id))
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 统计结算结果,并在数据库中添加销售记录以及销售明细记录
        /// </summary>
        private void CalculatedExpenditure()
        {
            //获取销售流水数据
            Sales sales = new Sales();
            sales.Amount = this.tb_Receivable.Text;
            sales.SalesmanID = this.cb_Guid.Text.Split('-')[0];
            sales.CashierID = this.User.UserID;
            sales.ReceiptsCode = DateTime.Now.ToString("yyyyMMddhhmmss");
            sales.SalesDate = DateTime.Now;
            sales.Profit = CalculationProfit().ToString("#0.00");

            //插入记录
            InsertAllRecord(sales);

            //计算找零
            double res = Math.Round(double.Parse(this.tb_Actual.Text) - double.Parse(this.tb_Receivable.Text), 2);
            if (res < 0) res = 0;
            this.lb_GiveChange.Text = res.ToString("#0.00") + "元";
            this.lb_SumPrice.Text = "合计:¥" + this.tb_Receivable.Text + "元";
            this.lb_GoodsNum.Text = "商品数量" + CalculationGoodsCount();
            this.lb_Serial.Text = sales.ReceiptsCode;
        }

        /// <summary>
        /// 向销售明细清单插入应有记录
        /// </summary>
        /// <param name="SalesID">销售记录的</param>
        /// <returns></returns>
        private void InsertAllRecord(Sales sales)
        {
            Cashier.InsertSalesRecord(sales);
            string salesid = Cashier.ReturnFinalSalesID(sales.ReceiptsCode);
            foreach (DataGridViewRow item in this.dgv_SettlementList.Rows)
            {
                SalesDetail det = new SalesDetail();
                det.GoodsID = item.Cells["cm_GoodsID"].Value.ToString();
                det.SalesID = salesid;
                det.Quantity = item.Cells["cm_Num"].Value.ToString();
                det.AloneAmount = double.Parse(item.Cells["cm_DiscountedPrice"].Value.ToString());
                Cashier.InsertSalesDetail(det);
                Cashier.UpdateGoodsQuantity(det.GoodsID,int.Parse(det.Quantity));
            }
        }

        /// <summary>
        /// 根据数据表统计应收框的价格
        /// </summary>
        private void Statistics()
        {
            if (this.dgv_SettlementList.Rows.Count == 0)
            {
                DataClear();
                return;
            }
            double sum = 0;
            foreach (DataGridViewRow item in this.dgv_SettlementList.Rows)
            {
                string st = item.Cells["cm_DiscountedPrice"].Value.ToString();
                double price = double.Parse(st);
                double num = double.Parse(item.Cells["cm_Num"].Value.ToString());
                sum += price * num;
            }
            this.tb_Receivable.Text = Math.Round(sum, 2).ToString("#0.00");
        }

        /// <summary>
        /// 计算该单总利润
        /// </summary>
        /// <returns></returns>
        private double CalculationProfit()
        {
            double sum = 0;
            foreach (DataGridViewRow item in this.dgv_SettlementList.Rows)
            {
                double d1 = (double.Parse(item.Cells["cm_DiscountedPrice"].Value.ToString()) * double.Parse(item.Cells["cm_Num"].Value.ToString()));
                double d2 = (double.Parse(item.Cells["cm_BuyingPrice"].Value.ToString()) * double.Parse(item.Cells["cm_Num"].Value.ToString()));
                sum += d1 - d2;
            }
            return sum;
        }

        /// <summary>
        /// 计算商品数量
        /// </summary>
        /// <returns></returns>
        private int CalculationGoodsCount()
        {
            int sum = 0;
            foreach (DataGridViewRow row in this.dgv_SettlementList.Rows)
            {
                sum += int.Parse(row.Cells["cm_Num"].Value.ToString());
            }
            return sum;
        }

        /// <summary>
        /// 重置所有数据
        /// </summary>
        private void DataClear()
        {
            this.dgv_SettlementList.Rows.Clear();
            this.tb_Actual.Text = string.Empty;
            this.tb_Receivable.Text = string.Empty;
            this.lb_Serial.Text = string.Empty;
            this.lb_SumPrice.Text = "合计:¥0.00元";
            this.lb_GoodsNum.Text = "商品数量:0";
            this.lb_GiveChange.Text = "0元";
        }
        #endregion

    }
}
